﻿using CF.CFLog;
using UnityEngine;

namespace CF.Core
{
    /// <summary>
    /// Mono Behaviour Singleton
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
    {
        protected static T instance = null;

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = FindObjectOfType<T>();

                    if (FindObjectsOfType<T>().Length > 1)
                    {
                        Log.Error($"有多个实例化对象: {typeof(T).Name}");
                        return instance;
                    }

                    if (instance == null)
                    {
                        var instanceName = typeof(T).Name;
                        var instanceGo = new GameObject(instanceName);
                        instance = instanceGo.AddComponent<T>();
                        DontDestroyOnLoad(instanceGo);
                    }
                }

                return instance;
            }
        }

        protected virtual void Awake()
        {
            instance = (T) this;
        }

        protected virtual void OnDestroy()
        {
            instance = null;
        }
    }
}